package com.sgb.kjwl.view.ui.activity.leaseAsk;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityMachineOut3Binding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.MachineDetailEntity;
import com.sgb.kjwl.utils.AbScreenUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.kjwl.view.ui.activity.house.LeaseInviteActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.AuthActivity3;
import com.sgb.kjwl.view.ui.activity.self.publish.GetPositionActivity;
import com.sgb.kjwl.view.ui.activity.self.publish.MachinePublishOutActivity;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.machine.MachineDetailModel;
import com.stx.xhb.androidx.XBanner;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MDateUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

/**
 * 机械详情(出租)
 *(原生界面暂时废弃,现对接为H5)
 * @author 008
 */
@Deprecated
public class MachineOutActivity extends AppActivity {

    private ActivityMachineOut3Binding binding;
    @Inject
    MachineDetailModel viewModel;
    private MachineDetailEntity data;

    private String status = "";
    private String type = "";//type 为空时代表是从租赁首页列表进入的详情
    private String id;
    private boolean isOff = false;//是否被关注

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent).machineModule(new MachineModule(this)).build().inject(this);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.setClass(context, MachineOutActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String id, String type) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("type", type);
        intent.setClass(context, MachineOutActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        this.id = getIntent().getStringExtra("id");
        viewModel.getDetailModel(id);
        viewModel.judgeLease(id);

        type = getIntent().getStringExtra("type");
        if ("1".equals(type)) {//上架
            binding.bidLayout.setVisibility(View.GONE);
            binding.bidLayout2.setVisibility(View.VISIBLE);
            binding.tvCallContact.setVisibility(View.GONE);
            binding.tvEdit.setVisibility(View.GONE);
            binding.tvDelete.setVisibility(View.GONE);
            binding.line.setVisibility(View.GONE);
            binding.line1.setVisibility(View.GONE);
        } else if ("2".equals(type)) {//下架
            binding.bidLayout.setVisibility(View.GONE);
            binding.bidLayout2.setVisibility(View.VISIBLE);
            binding.tvCallContact.setVisibility(View.GONE);
            binding.layoutEdit.setVisibility(View.VISIBLE);
            binding.tvDown.setText("上架");
        } else {
            binding.bidLayout.setVisibility(View.VISIBLE);
            binding.bidLayout2.setVisibility(View.GONE);
        }

    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_machine_out3);
        binding.include.ivBack.setOnClickListener(v -> finish());
        binding.include.titleView.setText("机械详情(出租)");
        binding.tvCallContact.setOnClickListener(this);
        binding.tvCall.setOnClickListener(this);
        binding.tvLook.setOnClickListener(this);
        binding.tvContactService.setOnClickListener(this);
        binding.tvInquireByLetter.setOnClickListener(this);
        binding.tvGz.setOnClickListener(this);
        binding.tvDelete.setOnClickListener(this);
        binding.tvDown.setOnClickListener(this);
        binding.tvEdit.setOnClickListener(this);
        binding.map.setOnClickListener(this);
        //网站
        binding.tvMachineNet.setOnClickListener(this);
        //询价
        binding.tvMachineInquiry.setOnClickListener(this);
        //邀请
        binding.tvMachineInvitation.setOnClickListener(this);
        binding.tvApply.setOnClickListener(this);
    }

    public void refreshData() {
        viewModel.getDetailModel(getIntent().getStringExtra("id"));
    }

    public void showDetail(MachineDetailEntity data) {
        this.data = data;
        if (!TextUtils.isEmpty(type)) {
            status = data.getStatus();
            if ("1".equals(status)) {//上架
                binding.tvCallContact.setVisibility(View.GONE);
                binding.tvEdit.setVisibility(View.GONE);
                binding.tvDelete.setVisibility(View.GONE);
                binding.line.setVisibility(View.GONE);
                binding.line1.setVisibility(View.GONE);
                binding.tvDown.setText("下架");
                binding.tvGz.setVisibility(View.INVISIBLE);
            } else if ("2".equals(status)) {//下架
                binding.tvCallContact.setVisibility(View.GONE);
                binding.layoutEdit.setVisibility(View.VISIBLE);
                binding.tvDelete.setVisibility(View.VISIBLE);
                binding.tvEdit.setVisibility(View.VISIBLE);
                binding.tvDown.setText("上架");
                binding.tvGz.setVisibility(View.INVISIBLE);

            }
        }

        binding.setViewModel(viewModel);
        viewModel.detail.set(data);
        if (!TextUtils.isEmpty(data.getDescribe())) {
            binding.tvDetail.setText(data.getDescribe());

        } else {
            binding.tvDetail.setText("暂无描述");
        }

        binding.tvTitle.setText(data.getTitle());

        binding.banner.setBannerData(data.getPictures());
        //加载广告图片
        binding.banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                Glide.with(UiUtil.getContext()).load(data.getPictures().get(position)).into((ImageView) view);
            }
        });

        binding.tvUpdate.setText("更新时间：" + timeStamp2Date(data.getUpdateTime(), "yyyy-MM-dd"));
        if (!TextUtils.isEmpty(data.getWorkStartTime()) && !TextUtils.isEmpty(data.getWorkEndTime())) {
            binding.tvAllowTimeDetail.setText(MDateUtil.getByTimestamp(Long.parseLong(data.getWorkStartTime()), MDateUtil.Format.FORMART6.name) + "—" + MDateUtil.getByTimestamp(Long.parseLong(data.getWorkEndTime()), MDateUtil.Format.FORMART6.name));
        } else {
            binding.tvAllowTimeDetail.setText("暂无选择");
        }

        if ("1".equals(data.getNeedInvoice())) {
            if ("0".equals(data.getInvoiceType())) {
                binding.tvInvoiceDetail.setText("普通发票，" + data.getTariff() + "%");
            } else {
                binding.tvInvoiceDetail.setText("专用发票，" + data.getTariff() + "%");
            }
        } else {
            binding.tvInvoiceDetail.setText("否");
        }
        binding.tvPrice.setText(data.getNegotiable() == 1 ? "面议" : data.getRentalPrice() + " " + data.getPriceUnit());
        binding.tvDriver.setText(data.getDriver().equals("1") ? "是" : "无");

        if (data.getDriver().equals("1")) {
            binding.clDriver.setVisibility(View.VISIBLE);
        } else {
            binding.clDriver.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(data.getRepairRemake())) {
            binding.tvRepair1.setText("暂无说明");
        } else {
            binding.tvRepair1.setText(data.getRepairRemake());
        }

        if (TextUtils.isEmpty(data.getFuelRemake())) {
            binding.tvRepair2.setText("暂无说明");
        } else {
            binding.tvRepair2.setText(data.getFuelRemake());
        }

        if (data.getAttrs() != null && data.getAttrs().size() > 0) {
            SpannableStringBuilder str = new SpannableStringBuilder("");
            for (int i = 0; i < data.getAttrs().size(); i++) {
                MachineDetailEntity.AttrsBean entity = data.getAttrs().get(i);
                str.append(entity.getName() + " " + entity.getVal() + "" + entity.getUnit() + ", ");
            }
            binding.tvKey.setText(str.toString().substring(0, str.toString().lastIndexOf(",")));

        }

        if (TextUtils.isEmpty(type)) {
            //设置隐藏电话号码中间四位
            binding.tvPhone.setText(settingPhone(data.getContactNumber()));
            binding.tvLook.setVisibility(View.VISIBLE);
        } else {
            binding.tvPhone.setText(data.getContactNumber());
            binding.tvLook.setVisibility(View.GONE);
        }

        if(TextUtils.isEmpty(data.getCompanyName())){
            binding.tvApply.setVisibility(View.GONE);
            binding.tvMachineNet.setVisibility(View.GONE);
            binding.tvMachineInvitation.setVisibility(View.GONE);
        }else{
            binding.tvApply.setVisibility(View.VISIBLE);
            binding.tvMachineNet.setVisibility(View.VISIBLE);
            binding.tvMachineInvitation.setVisibility(View.VISIBLE);
        }

    }


    /**
     * 隐藏电话号码中间4位
     *
     * @param phone
     * @return
     */
    public String settingPhone(String phone) {
        if (!TextUtils.isEmpty(phone)) {
            if (phone.length() == 11) { //设置隐藏手机号码
                String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                return phone_s;
            } else if (phone.length() > 7) {//设置隐藏座机号码
                String phone_s = phone.substring(0, 3) + "****" + phone.substring(7);
                return phone_s;
            }
        }
        return "";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map:
                try {
                    Double lat = Double.valueOf(data.getLatitude());
                    Double lng = Double.valueOf(data.getLongitude());
                    GetPositionActivity.start(getActivity(), lng, lat, data.getAddressDetail());
                } catch (Exception e) {
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_call:
            case R.id.tv_call_contact:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    boolean manager = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                    if (manager) {
                        showDialogs(3);//电话
                    } else {
                        showDialogs(2);//未认证
                    }
                }
                break;
            case R.id.tv_look://查看联系方式
                //判断用户是否已登录,若已登录,允许查看联系方式,否则提示登录
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (data != null && !TextUtils.isEmpty(data.getContactNumber())) {
                        binding.tvPhone.setText(data.getContactNumber());
                    }
                }
                break;
            case R.id.tv_contact_service://交流
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    if (!TextUtils.isEmpty(data.getImAccount())) {
                        viewModel.judgeCompanyOrSelf(data.getImAccount(), data.getCompanyNo(), data.getCreatesuerNo());
                    } else {
                        checkAllowDialog("对方未设置客服人员，不支持交流。");
                    }
                }
                break;
            case R.id.tv_inquire_by_letter://函询
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    viewModel.checkAllowZlQuestion(data.getId(), "ZL", data.getCompanyNo(), data.getCreatesuerNo(), "1");
//                    PickInquireByLetterActivity.start(MachineOutActivity.this, data.getId(), "ZL", data.getCompanyNo(), data.getCreatesuerNo(), "2");
                }
                break;
            case R.id.tv_gz://关注
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    try {
                        Map<String, String> map = new HashMap<>();
                        map.put("businessNo", id);
                        map.put("type", "1");
//                        map.put("firstCategory", "");
//                        map.put("secondCategory", "");
                        viewModel.leaseFocus(map);
                    } catch (Exception e) {
                    }
                }
                break;
            case R.id.tv_delete:
                showDialogs(4);//删除
                break;
            case R.id.tv_down:
                if (status.equals("1")) {//上架
                    showDialogs(5);
                } else if (status.equals("2")) {//下架
                    showDialogs(6);
                }
                break;
            case R.id.tv_edit:
                //编辑
                EventBus.getDefault().postSticky(MachinePublishEvent.make().setMessageTag(EventConstant.EVENT_PUBLISH_MACHINE_OUT_EDIT).setMessageData(getIntent().getStringExtra("id")));
                MachinePublishOutActivity.start(MachineOutActivity.this);
                break;
            case R.id.tv_machine_net: // 网络
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), data.getCompanyId(), data.getCompanyNo(), 1, 0);
                break;
            //询价
            case R.id.tv_machine_inquiry:
                MToast.showToast(this, R.string.machine_incomplete);
                break;
            case R.id.tv_machine_invitation: //邀请
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    EventBus.getDefault().postSticky("transport_to_login");
                } else {
                    String manager = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ENTERPRISE_AUTH, "");
                    if (manager.equals("SUCCESS")) {
                        String myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
                        if (myCompanyNo.equals(data.getCompanyNo())) {
                            MToast.showToast(this, "同企业不可邀请");
                            return;
                        }
                        LeaseInviteActivity.start(this, data.getCompanyNo(), data.getCompanyName());
                    } else {
                        showDialogs(7);
                    }
                }
                break;
            case R.id.tv_apply://申请
                MToast.showToast(this, R.string.machine_incomplete);
                break;
            default:
                break;
        }
    }

    //认证dialog
    private void showDialogs(final int type) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_title.setVisibility(View.VISIBLE);
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);

        if (type == 1) {
            tv_title.setText("温馨提示");
            tv_message.setText("登录后可拨打电话，去登录");
        } else if (type == 2) {
            tv_title.setText("温馨提示");
            tv_message.setText("认证后可拨打电话,去认证");
        } else if (type == 3) {
            tv_title.setText("确认呼叫");
            tv_message.setText(data.getContactNumber() + "");
        } else if (type == 4) {
            tv_title.setText("确认删除");
        } else if (type == 5) {
            tv_title.setText("确认下架");
            tv_message.setText("下架后该车辆将无法被其他用户使用");
        } else if (type == 6) {
            tv_title.setText("确认上架");
        } else if (type == 7) {
            tv_title.setText("温馨提示");
            tv_message.setText("要先认证为企业用户才能邀请！");
        }

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == 2) {
                    AuthActivity.start(getActivity());
                } else if (type == 3) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:" + data.getContactNumber()));
                    startActivity(intent);
                } else if (type == 4) {
                    viewModel.getDeleteModel(data.getId(), status);
                } else if (type == 5) {
                    //已上架机械，下架操作
                    viewModel.getOnlineModel(data.getId(), "2");
                } else if (type == 6) {
                    //已上架机械，上架操作
                    viewModel.getOnlineModel(data.getId(), "1");
                } else if (type == 7) {
                    AuthActivity3.start(MachineOutActivity.this);
                }
                roundCornerDialog.dismiss();
            }
        });

        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });

    }


    public void checkAllowDialog(String msg) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);

        tv_logout_cancel.setVisibility(View.GONE);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("提示");

        tv_message.setText(msg);

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }


    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }


    //设置关注图标
    public void setTvGz(boolean b) {
        this.isOff = b;
        //是否关注
        if (isOff) {
            binding.tvGz.setSelected(true);
            binding.tvGz.setText("已关注");
            int padding = AbScreenUtils.dp2px(this, 6);
            binding.tvGz.setPadding(padding, 0, padding, 0);
        } else {
            binding.tvGz.setSelected(false);
            binding.tvGz.setText("关注");
            int padding = AbScreenUtils.dp2px(this, 12);
            binding.tvGz.setPadding(padding, 0, padding, 0);
        }
    }

    public void setLeaseFocus() {
        if (isOff) {
            MToast.showToast(this, "取消关注成功");
        } else {
            MToast.showToast(this, "关注成功");
        }
        setTvGz(!isOff);
    }
}
